// 声破天个人中心页面JavaScript

document.addEventListener('DOMContentLoaded', function() {
    // 加载用户资料
    loadUserProfile();
    
    // 初始化选项卡切换
    initTabSwitching();
    
    // 初始化页面滚动处理
    initScrollForElement('.content');
    
    // 初始化顶部栏滚动隐藏
    initTopBarScrollHandling();
    
    // 初始化播放器功能
    initPlayerCoverClick();
});

/**
 * 加载用户个人资料
 */
function loadUserProfile() {
    // 获取容器
    const container = document.getElementById('profile-content');
    if (!container) return;
    
    // 清除加载占位符
    container.innerHTML = '';
    
    // 尝试获取当前登录用户
    const currentUser = getCurrentUser();
    
    if (!currentUser) {
        // 用户未登录，显示登录提示
        showLoginRequired(container);
    } else {
        // 用户已登录，加载个人资料
        createUserProfileUI(currentUser, container);
    }
}

/**
 * 获取当前登录的用户
 * @returns {Object|null} 用户对象或null
 */
function getCurrentUser() {
    try {
        // 尝试从localStorage获取用户数据
        const userJson = localStorage.getItem('shengpotian_current_user') || localStorage.getItem('currentUser');
        const user = userJson ? JSON.parse(userJson) : null;
        
        // 确保头像路径是本地路径
        if (user && (!user.avatar || !user.avatar.startsWith('assets/'))) {
            user.avatar = 'assets/images/avatars/default.png';
            
            // 更新存储的用户数据
            localStorage.setItem('currentUser', JSON.stringify(user));
            if (localStorage.getItem('shengpotian_current_user')) {
                localStorage.setItem('shengpotian_current_user', JSON.stringify(user));
            }
        }
        
        return user;
    } catch (error) {
        console.error('获取用户数据出错:', error);
        return null;
    }
}

/**
 * 显示需要登录的提示
 * @param {HTMLElement} container 内容容器
 */
function showLoginRequired(container) {
    container.innerHTML = `
        <div class="login-required">
            <h2>请登录以查看您的个人资料</h2>
            <p>登录后可以查看您的个人资料、播放列表和收藏歌曲</p>
            <div class="login-buttons">
                <a href="login.html" class="login-button">登录</a>
                <a href="register.html" class="login-button outline">注册</a>
            </div>
        </div>
    `;
}

/**
 * 创建用户资料界面
 * @param {Object} user 用户对象
 * @param {HTMLElement} container 内容容器
 */
function createUserProfileUI(user, container) {
    // 创建头部信息
    const header = document.createElement('div');
    header.className = 'profile-header';
    
    // 确保用户对象存在所有必要的字段，防止undefined错误
    const safeUser = {
        username: user.username || '用户',
        email: user.email || '',
        avatar: user.avatar || 'assets/images/avatars/default.png',
        createdAt: user.createdAt || new Date().toISOString(),
        isPremium: user.isPremium || false,
        premiumPlan: user.premiumPlan || '',
        premiumExpiry: user.premiumExpiry || '',
        playlists: user.playlists || [],
        favorites: user.favorites || []
    };
    
    // 生成加入日期文本
    const joinDate = new Date(safeUser.createdAt);
    const joinDateText = joinDate.getFullYear() + '年' + 
                         (joinDate.getMonth() + 1) + '月' + 
                         joinDate.getDate() + '日加入';
    
    // 获取用户播放列表和收藏数量                
    const playlistCount = safeUser.playlists.length;
    const favoritesCount = safeUser.favorites.length;
    
    // 设置头部内容
    header.innerHTML = `
        <div class="profile-avatar">
            <img src="${safeUser.avatar}" alt="${safeUser.username}" onerror="this.src='assets/images/avatars/default.png'">
        </div>
        <div class="profile-info">
            <div class="profile-type">${safeUser.isPremium ? '<span class="premium-badge">Premium用户</span>' : '个人用户'}</div>
            <h1 class="profile-name">${safeUser.username}</h1>
            <div class="profile-email">${safeUser.email}</div>
            <div class="profile-join-date">${joinDateText}</div>
            
            <div class="profile-stats">
                <div class="stat-item">
                    <div class="stat-number">${playlistCount}</div>
                    <div class="stat-label">播放列表</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">${favoritesCount}</div>
                    <div class="stat-label">收藏歌曲</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">0</div>
                    <div class="stat-label">关注</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">0</div>
                    <div class="stat-label">粉丝</div>
                </div>
            </div>
            
            <div class="profile-actions">
                <button class="profile-btn edit-profile-btn">编辑个人资料</button>
                ${!safeUser.isPremium ? '<a href="premium.html" class="profile-btn premium-btn">升级到Premium</a>' : ''}
            </div>
        </div>
    `;
    
    // 创建内容区域
    const content = document.createElement('div');
    content.className = 'profile-content';
    
    // 如果用户不是高级会员，添加升级横幅
    if (!safeUser.isPremium) {
        const premiumBanner = document.createElement('div');
        premiumBanner.className = 'premium-banner';
        premiumBanner.innerHTML = `
            <div class="premium-banner-content">
                <h3>升级到声破天 Premium</h3>
                <p>无广告打扰，离线播放，更高音质，解锁更多功能</p>
            </div>
            <button class="premium-banner-button" onclick="window.location.href='premium.html'">立即升级</button>
        `;
        content.appendChild(premiumBanner);
    }
    
    // 添加导航选项卡
    const navigation = document.createElement('div');
    navigation.className = 'profile-navigation';
    navigation.innerHTML = `
        <div class="profile-nav-tabs">
            <div class="profile-nav-tab active" data-target="tab-overview">概览</div>
            <div class="profile-nav-tab" data-target="tab-playlists">播放列表</div>
            <div class="profile-nav-tab" data-target="tab-favorites">收藏</div>
            <div class="profile-nav-tab" data-target="tab-followers">粉丝</div>
            <div class="profile-nav-tab" data-target="tab-following">关注</div>
            <div class="profile-nav-tab" data-target="tab-activity">动态</div>
            ${safeUser.isPremium ? '<div class="profile-nav-tab premium-tab" data-target="tab-subscription">会员订阅</div>' : ''}
        </div>
    `;
    content.appendChild(navigation);
    
    // 创建各个标签页内容容器
    const overviewTab = document.createElement('div');
    overviewTab.className = 'tab-content';
    overviewTab.id = 'tab-overview';
    overviewTab.innerHTML = createOverviewTabContent(safeUser);
    
    const playlistsTab = document.createElement('div');
    playlistsTab.className = 'tab-content';
    playlistsTab.id = 'tab-playlists';
    playlistsTab.style.display = 'none';
    playlistsTab.innerHTML = createPlaylistsTabContent(safeUser);
    
    const favoritesTab = document.createElement('div');
    favoritesTab.className = 'tab-content';
    favoritesTab.id = 'tab-favorites';
    favoritesTab.style.display = 'none';
    favoritesTab.innerHTML = createFavoritesTabContent(safeUser);
    
    const followersTab = document.createElement('div');
    followersTab.className = 'tab-content';
    followersTab.id = 'tab-followers';
    followersTab.style.display = 'none';
    followersTab.innerHTML = createFollowersTabContent(safeUser);
    
    const followingTab = document.createElement('div');
    followingTab.className = 'tab-content';
    followingTab.id = 'tab-following';
    followingTab.style.display = 'none';
    followingTab.innerHTML = createFollowingTabContent(safeUser);
    
    const activityTab = document.createElement('div');
    activityTab.className = 'tab-content';
    activityTab.id = 'tab-activity';
    activityTab.style.display = 'none';
    activityTab.innerHTML = createActivityTabContent(safeUser);
    
    const subscriptionTab = document.createElement('div');
    subscriptionTab.className = 'tab-content';
    subscriptionTab.id = 'tab-subscription';
    subscriptionTab.style.display = 'none';
    subscriptionTab.innerHTML = createSubscriptionTabContent(safeUser);
    
    // 添加所有标签页到内容区域
    content.appendChild(overviewTab);
    content.appendChild(playlistsTab);
    content.appendChild(favoritesTab);
    content.appendChild(followersTab);
    content.appendChild(followingTab);
    content.appendChild(activityTab);
    content.appendChild(subscriptionTab);
    
    // 添加到容器
    container.appendChild(header);
    container.appendChild(content);
    
    // 初始化事件监听
    initProfileEventListeners(container, safeUser);
}

/**
 * 创建"概览"选项卡内容
 * @param {Object} user 用户对象
 * @returns {string} HTML内容
 */
function createOverviewTabContent(user) {
    let html = '';
    
    // Premium订阅信息部分(如果是Premium用户)
    if (user.isPremium) {
        html += createPremiumInfoSection(user);
    }

    const playlistCount = user.playlists ? user.playlists.length : 0;
    const favoritesCount = user.favorites ? user.favorites.length : 0;
    
    // 播放列表部分
    html += `
        <div class="profile-section">
            <div class="section-header">
                <h2 class="section-title">我的播放列表</h2>
                <span class="section-action">创建新播放列表</span>
            </div>
            <div class="section-content playlists-grid">
                ${playlistCount > 0 ? 
                    (user.playlists.slice(0, 4).map(playlist => `
                        <div class="card">
                            <div class="card-img">
                                <img src="${playlist.cover || 'assets/images/covers/cover1.jpg'}" alt="${playlist.name}">
                                <div class="play-button">
                                    <i class="fas fa-play"></i>
                                </div>
                            </div>
                            <h3>${playlist.name}</h3>
                            <p>播放列表 • ${playlist.trackCount || 0}首歌曲</p>
                        </div>
                    `).join('')) : 
                    '<p class="empty-message">还没有创建任何播放列表</p>'
                }
            </div>
        </div>
    `;
    
    // 收藏部分
    html += `
        <div class="profile-section">
            <div class="section-header">
                <h2 class="section-title">收藏的歌曲</h2>
                <span class="section-action">查看全部</span>
            </div>
            <div class="section-content favorites-list">
                ${favoritesCount > 0 ? 
                    (user.favorites.slice(0, 5).map((track, index) => `
                        <div class="track-row">
                            <div class="track-number">${index + 1}</div>
                            <div class="track-info">
                                <div class="track-image">
                                    <img src="${track.cover || 'assets/images/categories/chinese.jpg'}" alt="${track.title}">
                                </div>
                                <div class="track-details">
                                    <div class="track-name">${track.title}</div>
                                    <div class="track-artist">${track.artist}</div>
                                </div>
                            </div>
                            <div class="track-album">${track.album || ''}</div>
                            <div class="track-duration">${track.duration || '0:00'}</div>
                        </div>
                    `).join('')) : 
                    '<p class="empty-message">还没有收藏任何歌曲</p>'
                }
            </div>
        </div>
    `;
    
    // 最近播放部分
    html += `
        <div class="profile-section">
            <div class="section-header">
                <h2 class="section-title">最近播放</h2>
            </div>
            <div class="section-content recent-tracks">
                <p class="empty-message">暂无最近播放记录</p>
            </div>
        </div>
    `;
    
    return html;
}

/**
 * 创建Premium订阅信息模块
 * @param {Object} user 用户对象
 * @returns {string} HTML内容
 */
function createPremiumInfoSection(user) {
    // 默认计划信息
    const userPlan = user.premiumPlan ? {
        name: user.premiumPlan,
        price: user.premiumPlan === '个人版' ? '18' : (user.premiumPlan === '家庭版' ? '28' : '24'),
        interval: '月'
    } : {
        name: 'Premium个人版',
        price: '18',
        interval: '月'
    };
    
    // 格式化到期日期
    let formattedExpiryDate = '永久';
    if (user.premiumExpiry) {
        const expiryDate = new Date(user.premiumExpiry);
        formattedExpiryDate = expiryDate.getFullYear() + '年' + 
                             (expiryDate.getMonth() + 1) + '月' + 
                             expiryDate.getDate() + '日';
    }
    
    return `
        <div class="profile-section premium-info-section">
            <div class="section-header">
                <h2 class="section-title">您的Premium会员</h2>
                <span class="section-action">管理会员</span>
            </div>
            <div class="section-content">
                <div class="premium-plan-info">
                    <div class="plan-icon">
                        <i class="fas fa-crown"></i>
                    </div>
                    <div class="plan-details">
                        <h3>${userPlan.name}</h3>
                        <p>${userPlan.price}元/${userPlan.interval}</p>
                        <p class="plan-expiry">到期日期：${formattedExpiryDate}</p>
                    </div>
                    <div class="plan-benefits">
                        <ul>
                            <li><i class="fas fa-check"></i> 无广告打扰</li>
                            <li><i class="fas fa-check"></i> 高音质播放</li>
                            <li><i class="fas fa-check"></i> 离线收听</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    `;
}

/**
 * 创建"播放列表"选项卡内容
 * @param {Object} user 用户对象
 * @returns {string} HTML内容
 */
function createPlaylistsTabContent(user) {
    const playlistCount = user.playlists ? user.playlists.length : 0;
    
    return `
        <div class="profile-section full-width">
            <div class="section-header">
                <h2 class="section-title">我的播放列表</h2>
                <span class="section-action">创建新播放列表</span>
            </div>
            <div class="section-content playlists-grid">
                ${playlistCount > 0 ? 
                    (user.playlists.map(playlist => `
                        <div class="card">
                            <div class="card-img">
                                <img src="${playlist.cover || 'assets/images/covers/cover2.jpg'}" alt="${playlist.name}">
                                <div class="play-button">
                                    <i class="fas fa-play"></i>
                                </div>
                            </div>
                            <h3>${playlist.name}</h3>
                            <p>播放列表 • ${playlist.trackCount || 0}首歌曲</p>
                        </div>
                    `).join('')) : 
                    `<div class="empty-content">
                        <p class="empty-message">还没有创建任何播放列表</p>
                        <button class="profile-btn">创建第一个播放列表</button>
                    </div>`
                }
            </div>
        </div>
    `;
}

/**
 * 创建"收藏歌曲"选项卡内容
 * @param {Object} user 用户对象
 * @returns {string} HTML内容
 */
function createFavoritesTabContent(user) {
    const favoritesCount = user.favorites ? user.favorites.length : 0;
    
    return `
        <div class="profile-section full-width">
            <div class="section-header">
                <h2 class="section-title">收藏的歌曲</h2>
                ${favoritesCount > 0 ? '<button class="profile-btn">播放全部</button>' : ''}
            </div>
            <div class="section-content">
                ${favoritesCount > 0 ? 
                    (user.favorites.map((track, index) => `
                        <div class="track-row">
                            <div class="track-number">${index + 1}</div>
                            <div class="track-info">
                                <div class="track-image">
                                    <img src="${track.cover || 'assets/images/categories/dance.jpg'}" alt="${track.title}">
                                </div>
                                <div class="track-details">
                                    <div class="track-name">${track.title}</div>
                                    <div class="track-artist">${track.artist}</div>
                                </div>
                            </div>
                            <div class="track-album">${track.album || ''}</div>
                            <div class="track-duration">${track.duration || '0:00'}</div>
                        </div>
                    `).join('')) :
                    `<div class="empty-content">
                        <p class="empty-message">您还没有收藏任何歌曲</p>
                        <button class="profile-btn">浏览音乐</button>
                    </div>`
                }
            </div>
        </div>
    `;
}

// 创建"粉丝"选项卡内容
function createFollowersTabContent(user) {
    return `
        <div class="profile-section full-width">
            <div class="section-header">
                <h2 class="section-title">我的粉丝</h2>
            </div>
            <div class="section-content">
                <p class="empty-message">暂无粉丝</p>
            </div>
        </div>
    `;
}

// 创建"关注"选项卡内容
function createFollowingTabContent(user) {
    return `
        <div class="profile-section full-width">
            <div class="section-header">
                <h2 class="section-title">我的关注</h2>
            </div>
            <div class="section-content">
                <p class="empty-message">暂无关注的用户</p>
            </div>
        </div>
    `;
}

// 创建"动态"选项卡内容
function createActivityTabContent(user) {
    return `
        <div class="profile-section full-width">
            <div class="section-header">
                <h2 class="section-title">我的动态</h2>
            </div>
            <div class="section-content">
                <p class="empty-message">暂无动态</p>
            </div>
        </div>
    `;
}

/**
 * 创建订阅标签页内容
 * @param {Object} user 用户对象
 * @returns {string} HTML内容
 */
function createSubscriptionTabContent(user) {
    // 如果用户不是Premium会员，显示升级提示
    if (!user.isPremium) {
        return `
            <div class="profile-section full-width">
                <div class="section-header">
                    <h2 class="section-title">会员订阅</h2>
                </div>
                <div class="section-content">
                    <div class="no-subscription">
                        <div class="premium-promo">
                            <div class="premium-logo">
                                <i class="fas fa-crown"></i>
                            </div>
                            <h3>升级到声破天Premium</h3>
                            <p>享受无广告音乐、离线收听和更多功能</p>
                            <a href="premium.html" class="profile-btn premium-btn">立即升级</a>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    // 为Premium会员显示订阅信息
    // 默认计划信息
    const userPlan = user.premiumPlan ? {
        name: user.premiumPlan,
        price: user.premiumPlan === '个人版' ? '18' : (user.premiumPlan === '家庭版' ? '28' : '24'),
        interval: '月',
        features: ['无广告', '高音质', '离线收听']
    } : {
        name: 'Premium个人版',
        price: '18',
        interval: '月',
        features: ['无广告', '高音质', '离线收听']
    };
    
    // 格式化到期日期
    let formattedExpiryDate = '永久';
    if (user.premiumExpiry) {
        const expiryDate = new Date(user.premiumExpiry);
        formattedExpiryDate = expiryDate.getFullYear() + '年' + 
                             (expiryDate.getMonth() + 1) + '月' + 
                             expiryDate.getDate() + '日';
    }
    
    // 生成支付历史
    const paymentHistory = [
        {
            date: '2023/10/01',
            plan: userPlan.name,
            amount: userPlan.price + '元',
            method: '支付宝',
            status: '成功'
        },
        {
            date: '2023/09/01',
            plan: userPlan.name,
            amount: userPlan.price + '元',
            method: '支付宝',
            status: '成功'
        }
    ];
    
    const paymentHistoryHTML = paymentHistory.map(payment => `
        <tr>
            <td>${payment.date}</td>
            <td>${payment.plan}</td>
            <td>${payment.amount}</td>
            <td>${payment.method}</td>
            <td><span class="status-success">${payment.status}</span></td>
        </tr>
    `).join('');
    
    return `
        <div class="profile-section full-width">
            <div class="section-header">
                <h2 class="section-title">会员订阅</h2>
            </div>
            <div class="subscription-content">
                <div class="current-subscription-info">
                    <div class="subscription-header">
                        <h3>当前订阅</h3>
                        <div class="subscription-status ${user.cancelPremium ? 'canceled' : 'active'}">
                            ${user.cancelPremium ? '已取消，到期后停止续费' : '自动续费'}
                        </div>
                    </div>
                </div>
                
                <div class="subscription-plan-details">
                    <div class="plan-icon">
                        <i class="fas fa-crown"></i>
                    </div>
                    <div class="plan-info">
                        <h4>${userPlan.name}</h4>
                        <p class="plan-price">${userPlan.price}元/${userPlan.interval || '月'}</p>
                        <p class="plan-expiry">到期时间：${formattedExpiryDate}</p>
                        <p class="plan-features">${userPlan.features ? userPlan.features.join(' · ') : '无广告 · 高音质 · 离线收听'}</p>
                    </div>
                </div>
                <div class="subscription-actions">
                    ${!user.cancelPremium ? `
                        <button class="cancel-subscription-btn" id="cancel-subscription">取消订阅</button>
                        <a href="premium.html" class="change-plan-btn">更改方案</a>
                    ` : `
                        <button class="resume-subscription-btn" id="resume-subscription">恢复订阅</button>
                        <a href="premium.html" class="change-plan-btn">更改方案</a>
                    `}
                </div>
            </div>
            
            <div class="payment-history">
                <h3>支付历史</h3>
                <table class="payment-history-table">
                    <thead>
                        <tr>
                            <th>日期</th>
                            <th>方案</th>
                            <th>金额</th>
                            <th>支付方式</th>
                            <th>状态</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${paymentHistoryHTML}
                    </tbody>
                </table>
            </div>
        </div>
    `;
}

// 初始化选项卡切换
function initTabSwitching() {
    const navTabs = document.querySelectorAll('.profile-nav-tab');
    const tabContents = document.querySelectorAll('.tab-content');
    
    // 为每个选项卡添加点击事件
    navTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除所有选项卡的活动状态
            navTabs.forEach(t => t.classList.remove('active'));
            
            // 添加当前选项卡的活动状态
            this.classList.add('active');
            
            // 获取目标内容ID
            const targetId = this.getAttribute('data-target');
            
            // 隐藏所有内容
            tabContents.forEach(content => {
                content.style.display = 'none';
            });
            
            // 显示目标内容
            const targetContent = document.getElementById(targetId);
            if (targetContent) {
                targetContent.style.display = 'block';
            }
        });
    });
    
    // 默认激活第一个选项卡
    // 检查URL参数中是否有指定的选项卡
    const urlParams = new URLSearchParams(window.location.search);
    const tabParam = urlParams.get('tab');
    
    if (tabParam) {
        // 找到对应的选项卡
        const targetTab = document.querySelector(`.profile-nav-tab[data-target="tab-${tabParam}"]`);
        if (targetTab) {
            targetTab.click();
        }
    }
}

// 初始化个人资料页事件监听
function initProfileEventListeners(container, user) {
    // 编辑个人资料按钮
    const editProfileBtn = container.querySelector('.edit-profile-btn');
    if (editProfileBtn) {
        editProfileBtn.addEventListener('click', function() {
            window.location.href = "settings.html"
        });
    }
    
    // 创建播放列表按钮
    const createPlaylistBtns = container.querySelectorAll('.section-action');
    createPlaylistBtns.forEach(btn => {
        if (btn.textContent.includes('创建')) {
            btn.addEventListener('click', function() {
                const playlistName = prompt('请输入播放列表名称');
                if (playlistName && playlistName.trim()) {
                    // 创建新播放列表
                    createNewPlaylist(user, playlistName.trim());
                }
            });
        }
    });
    
    // 初始化订阅按钮事件
    initSubscriptionButtons(container, user);
}

/**
 * 初始化订阅按钮事件
 */
function initSubscriptionButtons(container, user) {
    const cancelSubscriptionBtns = container.querySelectorAll('.cancel-subscription-btn');
    cancelSubscriptionBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            if (confirm('您确定要取消订阅吗？您将在当前计费周期结束后失去Premium权益。')) {
                // 设置用户取消订阅状态
                user.cancelPremium = true;
                
                // 更新用户数据
                updateUserInStorage(user);
                
                // 刷新页面
                alert('您的订阅将在当前计费周期结束后取消。');
                location.reload();
            }
        });
    });
    
    const resumeSubscriptionBtns = container.querySelectorAll('.resume-subscription-btn');
    resumeSubscriptionBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            if (confirm('您确定要恢复订阅吗？续费将在当前计费周期结束后继续。')) {
                // 取消用户的取消订阅状态
                user.cancelPremium = false;
                
                // 更新用户数据
                updateUserInStorage(user);
                
                // 刷新页面
                alert('您的订阅已恢复自动续费。');
                location.reload();
            }
        });
    });
}

// 创建新播放列表
function createNewPlaylist(user, playlistName) {
    const newPlaylist = {
        id: 'playlist_' + Date.now(),
        name: playlistName,
        cover: 'assets/images/covers/cover3.jpg',
        trackCount: 0,
        tracks: []
    };
    
    // 更新用户的播放列表
    updateUserPlaylists(user, newPlaylist);
    
    // 刷新页面
    alert(`播放列表"${playlistName}"创建成功！`);
    location.reload();
}

// 更新用户播放列表
function updateUserPlaylists(user, newPlaylist) {
    if (!user.playlists) {
        user.playlists = [];
    }
    
    user.playlists.push(newPlaylist);
    
    // 更新用户数据
    updateUserInStorage(user);
}

// 更新用户数据到本地存储
function updateUserInStorage(user) {
    // 更新当前用户
    localStorage.setItem('shengpotian_current_user', JSON.stringify(user));
    localStorage.setItem('currentUser', JSON.stringify(user));
    
    // 获取所有用户
    let users = JSON.parse(localStorage.getItem('shengpotian_users') || '[]');
    
    // 查找用户索引
    const userIndex = users.findIndex(u => u.id === user.id);
    
    // 如果找到用户，更新数据
    if (userIndex !== -1) {
        users[userIndex] = user;
        
        // 保存回存储
        localStorage.setItem('shengpotian_users', JSON.stringify(users));
    }
    
    // 同样更新新版本的users存储
    users = JSON.parse(localStorage.getItem('users') || '[]');
    const newUserIndex = users.findIndex(u => u.id === user.id);
    if (newUserIndex !== -1) {
        users[newUserIndex] = user;
        localStorage.setItem('users', JSON.stringify(users));
    }
}